<template>
  <div class="app-container">
    <div class="search">
      <!-- 搜索表单 -->
      <el-form :model="serchForm">
        <el-row>
          <div class="grid-content ep-bg-purple" />
          <el-form-item label="领域名称" prop="account">
            <el-input
              v-model="serchForm.model.areaTitle"
              placeholder="请输入领域名称"
              style="width: 200px"
            ></el-input>
          </el-form-item>

          <!-- <el-col :span="8"> -->
          <el-form-item label="状态">
            <el-select
              v-model="serchForm.model.shelfStatus"
              placeholder="请选择"
            >
              <el-option label="已上架" :value="1"></el-option>
              <el-option label="未上架" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <!-- </el-col> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQueryClick"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="handleResetClick">重置</el-button>
          </el-form-item>
        </el-row>
      </el-form>
      <!--重置 搜搜按钮 -->
      <div class="btns">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd(0)"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="toggleExpandAll"
              >展开/折叠</el-button
            >
          </el-col>
        </el-row>
      </div>
    </div>
    <el-table
      v-if="refreshTable"
      :data="dataList"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :default-expand-all="isExpandAll"
    >
      <el-table-column prop="areaTitle" label="领域名称"></el-table-column>
      <el-table-column prop="sort" label="排序" width="60"></el-table-column>
      <el-table-column prop="shelfStatus" label="状态">
        <template #default="scope">
          <el-tag v-if="scope.row.shelfStatus == 1" type="success" size="small">
            已上架
          </el-tag>
          <el-tag v-else type="danger" size="small"> 未上架 </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="areaContent"
        label="描述"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column prop="orderNum" label="图片">
        <template #default="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.files ? scope.row.files[0]?.filePath : ''"
            preview-teleported
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="
              scope.row.files ? mapImgUrl(scope.row.files) : ''
            "
            :initial-index="4"
            fit="cover"
          >
            <template #error>
              <div class="image-slot">
                <el-icon size="50"><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="210"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            icon="Plus"
            @click="handleAdd(scope.row)"
            >新增</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="title"
      v-model="open"
      width="680px"
      append-to-body
      @close="close"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="领域名称" prop="areaTitle">
              <el-input v-model="form.areaTitle" placeholder="请输入领域名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="领域描述" prop="areaContent">
              <el-input
                v-model="form.areaContent"
                placeholder="请输入领域描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number
                v-model="form.sort"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="图片" prop="files">
              <NewImgUpload
                tip="图片格式为jpg\png\gif，并校验图片像素不少于320*320,大小不超过2M,最多1张图片"
                :limit="1"
                @file-uploaded="handleImgUploaded"
                :Filelist="form.files"
                @file-remove="handleImgRemove"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="上架状态" prop="shelfStatus">
          <el-switch
            v-model="form.shelfStatus"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import NewImgUpload from "@/components/newImgUpload/newImgUpload";
import {
  saveDoaminRequest,
  getDomainListRequest,
  deleteDomainRequest,
} from "@/api/buildlibrary/domain.js";
import { rules } from "./rules";
import { ElMessage, ElMessageBox } from "element-plus";

let type = 42;

const serchForm = reactive({
  current: 1,
  size: 999,
  model: {
    type: type,
  },
});

const handleQueryClick = () => {
  getList();
};
const handleResetClick = () => {
  serchForm.current = 1;
  serchForm.size = 10;
  serchForm.model = {
    type: type,
  };
  getList();
};

let form = reactive({
  areaTitle: "",
  areaContent: "",
  sort: 0,
  files: [],
  shelfStatus: 1,
  parentId: 0, //顶级为0
  type: type, //分类类型 42按领域分类。43按专题分类
  delfiles: [],
});

let open = ref(false);

onMounted(() => {
  getList();
});

let totle = ref(0);
let dataList = ref([]);
const getList = async () => {
  const res = await getDomainListRequest(serchForm);
  console.log(res);
  dataList.value = res.data.records;
  totle.vlaue = res.data.total;
};

//新增分类
const handleAdd = (row) => {
  delete form.id;
  if (row === 0) {
    form.parentId = 0;
  } else {
    form.parentId = row.id;
  }

  console.log(row);

  open.value = true;
  nextTick(() => {
    formRef.value.clearValidate();
  });
};

//编辑分类
const handleUpdate = (row) => {
  form.id = row.id;
  form.parentId = row.parentId;
  form.type = row.type;
  form.sort = row.sort;
  form.areaTitle = row.areaTitle;
  form.areaContent = row.areaContent;
  form.shelfStatus = row.shelfStatus;
  form.files = row.files?.map((item) => {
    return {
      name: item.fileName,
      id: item.id,
      url: item.filePath,
      ...item,
    };
  });

  open.value = true;
};

const close = () => {
  form.areaTitle = "";
  form.areaContent = "";
  form.sort = 0;
  form.files = [];
  form.shelfStatus = 1;
  form.parentId = 0;
  form.type = type;
  form.delfiles = [];
  console.log(111);
  //清楚校验
  formRef.value.clearValidate();
};

//图片上传处理
const handleImgUploaded = (data) => {
  if (!form.files) {
    form.files = [];
  }
  form.files.push({
    fileId: data.id,
    fileName: data.name,
    fileSize: data.size,
    name: data.name,
    id: data.id,
    url: data.path,
  });
  formRef.value.validateField("files");

  // formRef.value.clearValidate();
};
//返回图片链接
const mapImgUrl = (data) => {
  return data.map((item) => {
    return item.filePath;
  });
};

let refreshTable = ref(true);
let isExpandAll = ref(false);
//展开
const toggleExpandAll = () => {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
};

//图片删除处理
const handleImgRemove = (data) => {
  // form.files.push({
  //   id: data.id,
  // });
  let fileId = "";
  console.log(data);
  if (data.fileId) {
    fileId = data.fileId;
  } else {
    fileId = data.response.data[0].id;
  }
  form.delfiles.push(fileId);

  form.files.forEach((item) => {
    console.log(item);
    if (item.fileId === fileId) {
      form.files.splice(item, 1);
      console.log(1);
    }
  });
  console.log(data.fileId);
};

let formRef = ref(null);
//表单提交
const submitForm = () => {
  if (formRef.value) {
    formRef.value.validate(async (valid) => {
      if (valid) {
        if (!form.id) {
          //新增
          console.log(form);
          const res = await saveDoaminRequest(form);
          if (res.data) {
            open.value = false;
            ElMessage.success("新增成功！");
            getList();
          }
          console.log(res);
        } else {
          //编辑
          console.log(form);
          form.files.forEach((item) => {
            delete item.filePath;
          });
          const res = await saveDoaminRequest(form);
          if (res.data) {
            open.value = false;
            ElMessage.success("编辑成功！");
            getList();
          }
          console.log(res);
        }
      } else {
        console.log("error submit!!");
        return false;
      }
    });
  }
};

//删除
const handleDelete = async (row) => {
  // console.log(row.id);
  // const res = await deleteDomainRequest(row.id);
  // if (res.data) {
  //   ElMessage.success("删除成功！");
  //   getList();
  // }
  // console.log(res);

  ElMessageBox.confirm('是否确认删除名称为"' + row.areaTitle + '"的数据项?')
    .then(function () {
      return deleteDomainRequest(row.id);
    })
    .then(() => {
      getList();
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
:deep(.el-form-item--default) {
  margin-right: 32px;
}
</style>
